//
//  ARTMainTabController.m
//  ChartsDemo
//
//  Created by 李光尧 on 2021/3/31.
//

#import "ARTMainTabController.h"
// controllers
//#import "ARTOximeterMonitorController.h"
//#import "ARTFetalHeartMonitorController.h"
#import "ARTWatchMonitorController.h"
//#import "ARTPlateauOximeterController.h"
#import "HistoryViewController.h"
#import "MineViewController.h"
//#import "ARTHomePageViewController.h"

@interface ARTMainTabController ()<UITabBarControllerDelegate>

// 返回按钮
@property (strong, nonatomic)  UIButton *backButton;
// 切换历史记录按钮
@property (strong, nonatomic)  UIButton *rightButton;

//@property (strong, nonatomic)  ARTOximeterMonitorController *oximeterVC;
//@property (strong, nonatomic)  ARTFetalHeartMonitorController *fetalHeartVC;
@property (strong, nonatomic)  ARTWatchMonitorController *watchVC;
//@property (strong, nonatomic)  ARTPlateauOximeterController *plateauVC;
@property (strong, nonatomic)  HistoryViewController *historyVC;
@property (strong, nonatomic)  MineViewController *mineVC;
//@property (strong, nonatomic)  ARTHomePageViewController *pelvicMusclesVC;

// 弹出框
//@property (strong, nonatomic)  QMUIPopupMenuView *meunView;
// itemMunu
@property (strong, nonatomic)  NSDictionary *menuDic;

@property (strong, nonatomic) NSArray *tabBarItems;

@end

@implementation ARTMainTabController

#pragma mark--THE LIFE CYCLE
-  (instancetype)init{
    self = [super init];
    if (!self) {
        return nil;
    }
    // init code
    [ARTSingle shareInstance].hadLoadTabVC = YES;
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self j_appearance];
    
    self.delegate =self;
    [self setupViewControllers];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(languageChange:) name:ART_Notify_LanguageChanged object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeSelect) name:APP_BECOME_TEST object:nil];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self didSelectWithIndex:self.selectedIndex];
//    if (_pelvicMusclesVC){
//        _pelvicMusclesVC.tabBarItem.title = FYLocalizedString(@"real_time", @"");
//    }
    if (_historyVC){
        _historyVC.tabBarItem.title = FYLocalizedString(@"history_record", @"");
    }
}

- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [ARTSingle shareInstance].hadLoadTabVC = YES;
}

- (void)dealloc{
    J_Remove_Notify(self);
}

- (void)setupViewControllers{
    [self.tabBar setBackgroundImage:[UIImage qmui_imageWithColor:[UIColor colorWithString:@"#ffffff"]]];
    self.tabBar.tintColor = [UIColor colorWithString:@"#0095B6"];
    
    self.tabBarItems = [NSMutableArray array];
    // 颜色配置
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    [attrs setValue:[UIFont systemFontOfSize:12] forKey:NSFontAttributeName];
    [attrs setValue:[UIColor colorWithString:@"#666666"] forKey:NSForegroundColorAttributeName];
    
    NSMutableDictionary *selectedAttrs = [NSMutableDictionary dictionary];
    [selectedAttrs setValue:[UIFont systemFontOfSize:12] forKey:NSFontAttributeName];
    [selectedAttrs setValue:[UIColor colorWithString:@"#0FCB81"] forKey:NSForegroundColorAttributeName];
    UITabBarItem *item = [UITabBarItem appearance];
    [item setTitleTextAttributes:attrs forState:UIControlStateNormal];
    [item setTitleTextAttributes:selectedAttrs forState:UIControlStateSelected];
    
    // 初始化
//    _oximeterVC = [ARTOximeterMonitorController new];
//    _oximeterVC.tabBarItem.title = FYLocalizedString(@"real_time", @"");
//    _oximeterVC.tabBarItem.image = [[UIImage imageNamed:@"tab_time_nor"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//    _oximeterVC.tabBarItem.selectedImage = [[UIImage imageNamed:@"tab_time_select"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
//    _fetalHeartVC = [[ARTFetalHeartMonitorController alloc]init];
//    _fetalHeartVC.tabBarItem.title = FYLocalizedString(@"real_time", @"");
//    _fetalHeartVC.tabBarItem.image = [[UIImage imageNamed:@"tab_time_nor"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//    _fetalHeartVC.tabBarItem.selectedImage = [[UIImage imageNamed:@"tab_time_select"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    _watchVC = [[ARTWatchMonitorController alloc]init];
    _watchVC.tabBarItem.title = FYLocalizedString(@"real_time", @"");
    _watchVC.tabBarItem.image = [[UIImage imageNamed:@"tab_time_nor"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    _watchVC.tabBarItem.selectedImage = [[UIImage imageNamed:@"tab_time_select"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
//    _plateauVC = [[ARTPlateauOximeterController alloc]init];
//    _plateauVC.tabBarItem.title = FYLocalizedString(@"real_time", @"");
//    _plateauVC.tabBarItem.image = [[UIImage imageNamed:@"tab_time_nor"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//    _plateauVC.tabBarItem.selectedImage = [[UIImage imageNamed:@"tab_time_select"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        
    //--
    _historyVC = [HistoryViewController new];
    _historyVC.tabBarItem.title = FYLocalizedString(@"history_record", @"");
    _historyVC.tabBarItem.image = [[UIImage imageNamed:@"tab_history_nor"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    _historyVC.tabBarItem.selectedImage = [[UIImage imageNamed:@"tab_history_select"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

    //--
    _mineVC = [MineViewController new];
    _mineVC.tabBarItem.title = FYLocalizedString(@"app__my", @"");
    _mineVC.tabBarItem.image = [[UIImage imageNamed:@"tab_me_nor"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    _mineVC.tabBarItem.selectedImage = [[UIImage imageNamed:@"tab_me_select"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
//    _pelvicMusclesVC = [ARTHomePageViewController new];
//    _pelvicMusclesVC.tabBarItem.title = @"实时";
//    _pelvicMusclesVC.tabBarItem.image = [[UIImage imageNamed:@"tab_time_nor"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//    _pelvicMusclesVC.tabBarItem.selectedImage = [[UIImage imageNamed:@"tab_time_select"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

//    self.viewControllers = @[
//        _fetalHeartVC,
//        _historyVC,
//        _mineVC
//    ];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.backButton];
    _backButton.hidden = YES;
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.rightButton];
//    _rightButton.hidden = YES;
}

- (void)setMonitorDevType:(ARTDeviceType)monitorDevType{
    _monitorDevType = monitorDevType;
    _historyVC.chooseDevType = monitorDevType;
    if (monitorDevType == ARTDeviceTypeOximeter) {
//        self.viewControllers = @[
//            _oximeterVC,
//            _historyVC,
//            _mineVC
//        ];
//        _tabBarItems = @[_oximeterVC.tabBarItem,_historyVC.tabBarItem,_mineVC.tabBarItem];
    }else if (monitorDevType == ARTDeviceTypeFetalHeart){
//        self.viewControllers = @[
//            _fetalHeartVC,
//            _historyVC,
//            _mineVC
//        ];
//        _tabBarItems = @[_fetalHeartVC.tabBarItem,_historyVC.tabBarItem,_mineVC.tabBarItem];
    }else if (monitorDevType == ARTDeviceTypeWatch){
        self.viewControllers = @[
            _watchVC,
            _historyVC,
            _mineVC
        ];
        _tabBarItems = @[_watchVC.tabBarItem,_historyVC.tabBarItem,_mineVC.tabBarItem];
    }else if (monitorDevType == ARTDeviceTypePlateau){
//        self.viewControllers = @[
//            _plateauVC,
//            _historyVC,
//            _mineVC
//        ];
//        _tabBarItems = @[_watchVC.tabBarItem,_historyVC.tabBarItem,_mineVC.tabBarItem];
    }else if (monitorDevType == ARTDeviceTypePelvicMuscles){ /// 盆底肌
//        self.viewControllers = @[
//            _pelvicMusclesVC,
//            _historyVC,
//            _mineVC
//        ];
    }
    [self didSelectWithIndex:self.selectedIndex];
}

#pragma mark--PRIVATE METHOD
- (void)changeSelect{
    self.selectedIndex = 0;
    [self didSelectWithIndex:self.selectedIndex];
}

- (void)didSelectWithIndex:(NSInteger)index{
    
    _backButton.hidden = !(index == 0);
    _rightButton.hidden = !(index == 1);
    [_backButton setImage:J_ImageNamed(@"i_return_black") forState:UIControlStateNormal];

    if (index == 0) {
        self.title = FYLocalizedString(@"real_time", @"");
        if (_monitorDevType == ARTDeviceTypeWatch) {
            self.title = FYLocalizedString(@"sleep_watch_name_", @"");
        }
        if (_monitorDevType == ARTDeviceTypeOximeter) {
            _rightButton.hidden = NO;
            BOOL canPlay = [NSUserDefaults jk_boolForKey:ART_Storage_VioceStatus];
            if (!canPlay) {
                [_rightButton setImage:J_ImageNamed(@"nav_ic_voice_on") forState:UIControlStateNormal];
            }else{
                [_rightButton setImage:J_ImageNamed(@"nav_ic_voice_off") forState:UIControlStateNormal];
            }
        }else if (_monitorDevType == ARTDeviceTypePlateau){
            _rightButton.hidden = NO;
            BOOL canPlay = [NSUserDefaults jk_boolForKey:ART_Storage_PlateauVioceStatus];
            if (!canPlay) {
                [_rightButton setImage:J_ImageNamed(@"nav_ic_voice_on") forState:UIControlStateNormal];
            }else{
                [_rightButton setImage:J_ImageNamed(@"nav_ic_voice_off") forState:UIControlStateNormal];
            }
        }else if (_monitorDevType == ARTDeviceTypePelvicMuscles) { /// 盆底肌
            self.title = @"";//FYLocalizedString(@"real_time", @"");
        }
    }else if (index == 1){
        if (_monitorDevType == ARTDeviceTypePelvicMuscles) { /// 盆底肌
            self.title = FYLocalizedString(@"pelvic_floor_history_record", @"");
        }else{
            self.title = FYLocalizedString(@"history_record", @"");
        }
        
        [_rightButton setImage:J_ImageNamed(@"nav_ic_more") forState:UIControlStateNormal];
        if (_monitorDevType == ARTDeviceTypeWatch) {
            _backButton.hidden = NO;
            [_backButton setImage:J_ImageNamed(@"nav_ic_refresh") forState:UIControlStateNormal];
        }
    }else{
        self.title = FYLocalizedString(@"app__my", @"");
    }
}

- (void)backClick{
    if (self.selectedIndex == 0) {
        if (_monitorDevType == ARTDeviceTypeOximeter || _monitorDevType == ARTDeviceTypePlateau) {
            [self backMethod];
        }
        else if (_monitorDevType == ARTDeviceTypeFetalHeart){
//            if (_fetalHeartVC.isRecording) {
//                [self lq_showAlertControllerWithMessage:FYLocalizedString(@"fhr_audio_exit", @"") cancleHandle:^{
//                    
//                } okHandle:^{
//                    [self backMethod];
//                }];
//            }else{
//                [self backMethod];
//            }
        }
        else if (_monitorDevType == ARTDeviceTypeWatch){
            [self backMethod];
        }
        else if (_monitorDevType == ARTDeviceTypePelvicMuscles){
            [self backMethod];
        }
    }else if (self.selectedIndex == 1){
        if (_monitorDevType == ARTDeviceTypeWatch) {
            NSLog(@"同步");
            [_watchVC syncWithWatchFile];
        }
    }
}

- (void)backMethod{
    [ARTSingle shareInstance].hadLoadTabVC = NO;
    [[NSNotificationCenter defaultCenter] postNotificationName:ART_Notify_RealTimeBack object:nil];
    // 将单利中的外设和特征值销毁掉
    [ARTSingleShare.baby cancelAllPeripheralsConnection];
    ARTSingleShare.currentCharacteristic = nil;
    ARTSingleShare.currentPeripheral = nil;
    ARTSingleShare.writeCharacteristic = nil;
//    if (!(_monitorDevType == ARTDeviceTypePlateau && _plateauVC.testModel)) {
        [self.navigationController popViewControllerAnimated:YES];
//    }
}

- (void)languageChange:(NSNotification *)notifi {
    for (int i = 0; i < self.tabBarItems.count; i ++) {
        UITabBarItem *item = self.tabBarItems[i];
        item.title = [self textByTabBarViewIndex:i];
    }
//    if (_pelvicMusclesVC){
//        _pelvicMusclesVC.tabBarItem.title = FYLocalizedString(@"real_time", @"");
//    }
    if (_historyVC){
        _historyVC.tabBarItem.title = FYLocalizedString(@"history_record", @"");
    }
}

- (NSString *)textByTabBarViewIndex:(NSInteger)index{
    NSString *text = @"";
    if (index == 0) {
        text = FYLocalizedString(@"real_time", @"");
        if (_monitorDevType == ARTDeviceTypeWatch) {
            text = FYLocalizedString(@"sleep_watch_name_", @"");
        }
    }else if (index == 1){
        text = FYLocalizedString(@"history_record", @"");
    }else if (index == 2){
        text = FYLocalizedString(@"app__my", @"");
    }
    return text;
}

- (void)rightAction:(UIButton *)sender{
    if (self.selectedIndex == 0) {
        if (_monitorDevType == ARTDeviceTypeOximeter){
            _rightButton.hidden = NO;
            BOOL canPlay = [NSUserDefaults jk_boolForKey:ART_Storage_VioceStatus];
            canPlay = !canPlay;
            [NSUserDefaults jk_setObject:@(canPlay) forKey:ART_Storage_VioceStatus];
            if (!canPlay) {
                [_rightButton setImage:J_ImageNamed(@"nav_ic_voice_on") forState:UIControlStateNormal];
            }else{
                [_rightButton setImage:J_ImageNamed(@"nav_ic_voice_off") forState:UIControlStateNormal];
            }
            return;
        }else if (_monitorDevType == ARTDeviceTypePlateau){
            _rightButton.hidden = NO;
            BOOL canPlay = [NSUserDefaults jk_boolForKey:ART_Storage_PlateauVioceStatus];
            canPlay = !canPlay;
            [NSUserDefaults jk_setObject:@(canPlay) forKey:ART_Storage_PlateauVioceStatus];
            if (!canPlay) {
                [_rightButton setImage:J_ImageNamed(@"nav_ic_voice_on") forState:UIControlStateNormal];
            }else{
                [_rightButton setImage:J_ImageNamed(@"nav_ic_voice_off") forState:UIControlStateNormal];
            }
            return;
        }
    }else if (self.selectedIndex == 1){
        if (_monitorDevType == ARTDeviceTypeFetalHeart) {
//            if (_fetalHeartVC.isRecording) {
//                [QMUITips showWithText:FYLocalizedString(@"fhr_audio_ing", @"")];
//                return;
//            }
//            if (_fetalHeartVC.currentPeripheral.state == CBPeripheralStateConnecting || _fetalHeartVC.currentPeripheral.state == CBPeripheralStateConnected) {
//                [self.view jk_makeToast:FYLocalizedString(@"pelvic_floor_while_connected", @"")];
//                return;
//            }
        }else if (_monitorDevType == ARTDeviceTypeOximeter){
//            if (_oximeterVC.currentPeripheral.state == CBPeripheralStateConnecting || _oximeterVC.currentPeripheral.state == CBPeripheralStateConnected) {
//                [self.view jk_makeToast:FYLocalizedString(@"pelvic_floor_while_connected", @"")];
//                return;
//            }
        }else if (_monitorDevType == ARTDeviceTypeWatch){
            if (_watchVC.currentPeripheral.state == CBPeripheralStateConnecting || _watchVC.currentPeripheral.state == CBPeripheralStateConnected) {
//                [self.view jk_makeToast:FYLocalizedString(@"pelvic_floor_while_connected", @"")];
                [QMUITips showWithText:FYLocalizedString(@"pelvic_floor_while_connected", @"")];
                return;
            }
        }else if (_monitorDevType == ARTDeviceTypePlateau){
//            if (_plateauVC.currentPeripheral.state == CBPeripheralStateConnecting || _plateauVC.currentPeripheral.state == CBPeripheralStateConnected) {
//                [self.view jk_makeToast:FYLocalizedString(@"pelvic_floor_while_connected", @"")];
//                return;
//            }
        }else if (_monitorDevType == ARTDeviceTypePelvicMuscles){
//            if (_pelvicMusclesVC.deviceConnecte) {
//                [self.view jk_makeToast:FYLocalizedString(@"pelvic_floor_while_connected", @"")];
//                return;
//            }
        }
    }
    
//    self.meunView.items = [self itemsForPopMenu];
//    self.meunView.sourceView = sender;
//    [self.meunView showWithAnimated:YES];
}

- (NSArray *)itemsForPopMenu{
    NSMutableArray *items = [NSMutableArray array];
    for (NSNumber *index in self.menuDic.allKeys) {
        if (index.integerValue != _monitorDevType) {
            [items addObject:[_menuDic objectForKey:index]];
        }
    }
    return items;
}

#pragma mark--UITabBarControllerDelegate
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewControlle {
    [self didSelectWithIndex:tabBarController.selectedIndex];
    if (tabBarController.selectedIndex == 1) {
        [_historyVC reloadData];
    }
}

#pragma mark--GETTER
- (UIButton *)backButton{
    if (!_backButton) {
        _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _backButton.frame = J_Frame(-10, 0, 47, 27);
        [_backButton setImage:J_ImageNamed(@"i_return_black") forState:UIControlStateNormal];
        [_backButton addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _backButton;
}

- (UIButton *)rightButton{
    if (!_rightButton) {
        _rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _rightButton.frame = J_FrameWithSize(30, 38);
        [_rightButton setImage:J_ImageNamed(@"nav_ic_more") forState:UIControlStateNormal];
        [_rightButton addTarget:self action:@selector(rightAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _rightButton;
}

//- (QMUIPopupMenuView *)meunView{
//    if (!_meunView) {
//        _meunView = [[QMUIPopupMenuView alloc] init];
//        _meunView.backgroundColor = [UIColor whiteColor];
//        // 点击空白地方消失浮层
//        _meunView.automaticallyHidesWhenUserTap = YES;
//        // 并且打开了 automaticallyHidesWhenUserTap 的情况下，可以修改背景遮罩的颜色
//        _meunView.maskViewBackgroundColor = [UIColor clearColor];//[[[UIColor blackColor] colorWithAlphaComponent:0.6]];
//        _meunView.shouldShowItemSeparator = YES;
//        _meunView.padding = UIEdgeInsetsMake(0, 30, 0, 30);
//        _meunView.itemSeparatorInset = UIEdgeInsetsMake(0, -30, 0, -30);
//        _meunView.arrowSize = CGSizeMake(0, 0);
//        _meunView.borderColor = [UIColor whiteColor];
//        _meunView.preferLayoutDirection = QMUIPopupContainerViewLayoutDirectionBelow;
//        _meunView.itemConfigurationHandler = ^(QMUIPopupMenuView *aMenuView, QMUIPopupMenuButtonItem *aItem, NSInteger section, NSInteger index) {
//            // 批量设置所有 item 的样式
//            [aItem.button setTitleColor:J_ColorFromHEX(0x666666) forState:UIControlStateNormal];
//            aItem.button.titleLabel.font = J_Font(14);
//        };
//        _meunView.didHideBlock = ^(BOOL hidesByUserTap) {
//        };
//    }
//    return _meunView;
//}

//- (NSDictionary *)menuDic{
////    if (!_menuDic) {
//        _menuDic = @{
//            @(ARTDeviceTypeOximeter):[QMUIPopupMenuButtonItem itemWithImage:nil title:FYLocalizedString(@"oxygen_name", @"") handler:^(QMUIPopupMenuButtonItem *aItem) {
//                self.monitorDevType = ARTDeviceTypeOximeter;
//                [aItem.menuView hideWithAnimated:YES];
//            }],
//            @(ARTDeviceTypeFetalHeart):[QMUIPopupMenuButtonItem itemWithImage:nil title:FYLocalizedString(@"fhr_name", @"") handler:^(QMUIPopupMenuButtonItem *aItem) {
//                self.monitorDevType = ARTDeviceTypeFetalHeart;
//                [aItem.menuView hideWithAnimated:YES];
//            }],
//            @(ARTDeviceTypeWatch):[QMUIPopupMenuButtonItem itemWithImage:nil title:FYLocalizedString(@"sleep_watch_name", @"") handler:^(QMUIPopupMenuButtonItem *aItem) {
//                self.monitorDevType = ARTDeviceTypeWatch;
//                [aItem.menuView hideWithAnimated:YES];
//            }],
//            @(ARTDeviceTypePlateau):[QMUIPopupMenuButtonItem itemWithImage:nil title:FYLocalizedString(@"Highland Pulse Oximeter", @"") handler:^(QMUIPopupMenuButtonItem *aItem) {
//                self.monitorDevType = ARTDeviceTypePlateau;
//                [aItem.menuView hideWithAnimated:YES];
//            }],
//            @(ARTDeviceTypePelvicMuscles):[QMUIPopupMenuButtonItem itemWithImage:nil title:FYLocalizedString(@"pelvic_floor_name_", @"") handler:^(QMUIPopupMenuButtonItem *aItem) {
//                self.monitorDevType = ARTDeviceTypePelvicMuscles;
//                [aItem.menuView hideWithAnimated:YES];
//            }]
//        };
////    }
//    return _menuDic;
//}


@end
